package com.caojing.syby.ui.home;


import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.caojing.syby.R;
import com.caojing.syby.base.BaseFragment;
import com.caojing.syby.bean.home.AdListBean;
import com.caojing.syby.bean.home.HomeGvBean;
import com.caojing.syby.bean.home.HomeTodayBean;
import com.caojing.syby.bean.home.HomeVpBean;
import com.caojing.syby.bean.home.RowsBean;
import com.caojing.syby.config.UrlConfig;
import com.caojing.syby.ui.adapter.HomeGvAdapter;
import com.caojing.syby.ui.adapter.HomePagerAdapter;
import com.caojing.syby.ui.details.searchdetails.SearchDetailActivity;
import com.caojing.syby.ui.details.viewpagerdetail.VpDetailActivity;
import com.caojing.syby.ui.search.SearchActivity;
import com.caojing.syby.ui.details.productdetail.ClickGridviewItemActivity;
import com.caojing.syby.view.MyGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment implements HomeContract.View {

    @Bind(R.id.home_fragment_iv_search)
    ImageView homeFragmentIvSearch;
    @Bind(R.id.home_fragment_vp)
    ViewPager homeFragmentVp;
    @Bind(R.id.home_fragment_iv_nz)
    LinearLayout homeFragmentIvNz;
    @Bind(R.id.home_fragment_iv_jj)
    LinearLayout homeFragmentIvJj;
    @Bind(R.id.home_fragment_iv_xb)
    LinearLayout homeFragmentIvXb;
    @Bind(R.id.home_fragment_iv_gd)
    LinearLayout homeFragmentIvGd;
    @Bind(R.id.home_fragment_iv_jrgx)
    ImageView homeFragmentIvJrgx;
    @Bind(R.id.home_fragment_iv_sjzb)
    ImageView homeFragmentIvSjzb;
    @Bind(R.id.home_fragment_iv_mzgh)
    ImageView homeFragmentIvMzgh;
    @Bind(R.id.home_fragment_iv_msh)
    ImageView homeFragmentIvMsh;
    @Bind(R.id.home_fragment_iv_zhfq)
    ImageView homeFragmentIvZhfq;
    @Bind(R.id.home_fragment_gv)
    MyGridView homeFragmentGv;
    @Bind(R.id.home_fragment_sv)
    PullToRefreshScrollView homeFragmentSv;
    private HomePresenter presenter;
    private HomePagerAdapter pagerAdapter;
    private HomeGvAdapter gvAdapter;
    private List<ImageView> ivlist;
    private LinearLayout llPoints;
    private List<RowsBean> totallist;
    private int PAGE = 1;
    private Handler handler = new Handler();
    public HomeFragment() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void onResume() {
        super.onResume();
        //让gridView失去焦点
        homeFragmentGv.setFocusable(false);
    }

    @Override
    protected void initView(View view) {
        llPoints = (LinearLayout) view.findViewById(R.id.ll_points);
        presenter = new HomePresenter(this);
        ivlist = new ArrayList<>();
        totallist = new ArrayList<>();
        gvAdapter = new HomeGvAdapter(totallist,getContext());
        homeFragmentGv.setAdapter(gvAdapter);
        /*scrollview监听器*/
        homeFragmentSv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                homeFragmentSv.onRefreshComplete();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                PAGE++;
                presenter.initGvData(initParams());
            }
        });
    }
    /*presenter加载数据*/
    @Override
    protected void initData() {
        presenter.initVpData();
        presenter.initTodayData();
        presenter.initGvData(initParams());
    }
    /*初始化initviewGvData参数*/
    public HashMap<String,String> initParams(){
        HashMap<String,String> params = new HashMap<>();
        params.put(UrlConfig.Key.ACT,UrlConfig.DefaultValue.ACT);
        params.put(UrlConfig.Key.V,UrlConfig.DefaultValue.V);
        params.put(UrlConfig.Key.PAGES,PAGE+"");
        return params;
    }
    /*首页viewpager初始化及自动无线轮播，加小圆点*/
    @Override
    public void onSuccessGetVp(HomeVpBean homeVpBean) {
        final List<AdListBean> adList = homeVpBean.getAdList();
        for (int i =0;i<adList.size();i++){
            ImageView iv = new ImageView(getContext());
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            Glide.with(this).load(adList.get(i).getImgUrl()).into(iv);
            ivlist.add(iv);
            final int finalI = i;
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), VpDetailActivity.class);
                    String headurl = adList.get(finalI).getImgUrl();
                    String address = adList.get(finalI).getAddress();
                    String name = adList.get(finalI).getCName();
                    intent.putExtra("headurl",headurl);
                    intent.putExtra("address",address);
                    intent.putExtra("name",name);
                    startActivity(intent);
                }
            });
        }
        initDots();
        pagerAdapter = new HomePagerAdapter(ivlist);
        homeFragmentVp.setAdapter(pagerAdapter);
        initViewPagerAuto();
    }

    @Override
    public void onFailGetVp(String msg) {
        Toast.makeText(getContext(),msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessGetToday(List<HomeTodayBean> list) {

        Glide.with(this).load(list.get(0).getImgUrl()).into(homeFragmentIvJrgx);
        Glide.with(this).load(list.get(1).getImgUrl()).into(homeFragmentIvSjzb);
        Glide.with(this).load(list.get(2).getImgUrl()).into(homeFragmentIvMsh);
        Glide.with(this).load(list.get(3).getImgUrl()).into(homeFragmentIvMzgh);
        Glide.with(this).load(list.get(4).getImgUrl()).into(homeFragmentIvZhfq);
    }

    @Override
    public void onFailGetToday(String msg) {
        Toast.makeText(getContext(),msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessGetGv(HomeGvBean homeGvBean) {
        totallist.addAll(homeGvBean.getRows());
        gvAdapter.notifyDataSetChanged();
        homeFragmentSv.onRefreshComplete();

        homeFragmentGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(getContext(), ClickGridviewItemActivity.class);
                RowsBean rowsBean = totallist.get(position);
                if (rowsBean != null) {
                    String spreadUrl = rowsBean.getSpreadUrl();
                    intent.putExtra("spreadUrl", spreadUrl);
                    String name = rowsBean.getName();
                    intent.putExtra("name",name);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    public void onFailGetGv(String msg) {
        Toast.makeText(getContext(),msg, Toast.LENGTH_SHORT).show();
    }
    @OnClick({R.id.home_fragment_iv_search, R.id.home_fragment_iv_nz, R.id.home_fragment_iv_jj, R.id.home_fragment_iv_xb, R.id.home_fragment_iv_gd, R.id.home_fragment_iv_jrgx, R.id.home_fragment_iv_sjzb, R.id.home_fragment_iv_mzgh, R.id.home_fragment_iv_msh, R.id.home_fragment_iv_zhfq})
    public void onClick(View view) {
        Intent showIntent = new Intent(getActivity(), SearchDetailActivity.class);
        switch (view.getId()) {
            case R.id.home_fragment_iv_search:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.home_fragment_iv_nz:
                showIntent.putExtra("sort",0);
                showIntent.putExtra("name","女裝");
                startActivity(showIntent);
                break;
            case R.id.home_fragment_iv_jj:
                showIntent.putExtra("sort",2);
                showIntent.putExtra("name","居家");
                startActivity(showIntent);
                break;
            case R.id.home_fragment_iv_xb:
                showIntent.putExtra("sort",4);
                showIntent.putExtra("name","鞋包");
                startActivity(showIntent);
                break;
            case R.id.home_fragment_iv_gd:
                Intent allIntent=new Intent(getContext(), SearchActivity.class);
                startActivity(allIntent);
                break;
            case R.id.home_fragment_iv_jrgx:
                showIntent.putExtra("sort",13);
                showIntent.putExtra("name","今日更新");
                startActivity(showIntent);
                break;
            case R.id.home_fragment_iv_sjzb:
                showIntent.putExtra("sort",7);
                showIntent.putExtra("name","手机周边");
                startActivity(showIntent);
                break;
            case R.id.home_fragment_iv_mzgh:
                showIntent.putExtra("sort",8);
                showIntent.putExtra("name","美妆个户");
                startActivity(showIntent);
                break;
            case R.id.home_fragment_iv_msh:
                showIntent.putExtra("sort",6);
                showIntent.putExtra("name","美食");
                startActivity(showIntent);
                break;
            case R.id.home_fragment_iv_zhfq:
                showIntent.putExtra("sort",14);
                showIntent.putExtra("name","最后疯抢");
                startActivity(showIntent);
                break;
        }
    }
    /*初始化viewpager的小圆点*/
    private void initDots() {
        for (int i = 0;i<ivlist.size();i++){
            View points = new View(getContext());
            points.setBackgroundResource(R.mipmap.dot_white);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15,15);
            params.leftMargin = 15;
            points.setLayoutParams(params);
            llPoints.addView(points);
        }
        llPoints.getChildAt(0).setBackgroundResource(R.mipmap.dot_black);
    }
    /*viewpager自动无线轮播*/
    private void initViewPagerAuto() {
        homeFragmentVp.setCurrentItem(1000*ivlist.size());
        homeFragmentVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                for (int i = 0;i<llPoints.getChildCount();i++){
                    llPoints.getChildAt(i).setBackgroundResource(R.mipmap.dot_white);
                    if ( i == position%ivlist.size()){
                        llPoints.getChildAt(i).setBackgroundResource(R.mipmap.dot_black);
                    }
                }
            }
        });
        Timer mTimer = new Timer();
        mTimer.schedule(new MyTimeTask(),2000);
    }
    /*定时器*/
    class  MyTimeTask extends TimerTask {
        private boolean isLoop = true;
        @Override
        public void run() {
            while (isLoop){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int currentItem =homeFragmentVp.getCurrentItem();
                        homeFragmentVp.setCurrentItem(++currentItem);
                    }
                });
            }
        }
    }

}
